package ch.mse.android.starbucksfinder;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import ch.mse.android.starbucksfinder.helper.GoogleMapsHelper;

public class LocationListActivity extends ListActivity{
	
	private Location ownLocation;
	private ArrayList<StarbucksLocation> starbucksLocationList;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.location_list);

		initPassedData();
		fillData();
	}

	@SuppressWarnings("unchecked")
	private void initPassedData() {
		Intent myIntent = this.getIntent();
		Bundle extras = myIntent.getExtras();
		ownLocation = new Location(Activity.LOCATION_SERVICE);
		ownLocation.setLatitude(extras.getDouble(MapActivity.LOCATION_LAT_KEY));
		ownLocation.setLongitude(extras.getDouble(MapActivity.LOCATION_LNG_KEY));
		starbucksLocationList = (ArrayList<StarbucksLocation>) extras.getSerializable(MapActivity.LOCATION_LIST_KEY);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Intent mapsRouteIntent = GoogleMapsHelper.getMapsRouteIntent(ownLocation, starbucksLocationList.get(position));
		startActivity(mapsRouteIntent);
	}
	
	
	private void fillData() {
		String[] locationStrings = new String[Math.min(starbucksLocationList.size(),10)];
		for (int i = 0; i < locationStrings.length; i++) {
			StarbucksLocation sbLoc = starbucksLocationList.get(i);
			int distance = Math.round(sbLoc.distanceTo(ownLocation));
			locationStrings[i] = sbLoc.toString() + "\nDistance: " + distance + "m";
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.locations_row, locationStrings );
		setListAdapter(adapter);
	}
}
